#include "dbmanager.h"


#define USER "root"
#define PSWD "asdf"
#define DB "stu_sql_test"
#define IP "127.0.0.1"

DBManager::DBManager()
{
    m_mysql = mysql_init(nullptr);
    if (!mysql_real_connect(m_mysql, IP, USER, PSWD, DB, 3306, nullptr, 0))
    {
        LOG << "MySQL connect failed:" << mysql_error(m_mysql);
    } else {
        LOG << "MySQL connected successfully";
        mysql_set_character_set(m_mysql, "utf8mb4");
    }
}

DBManager::~DBManager() {
    if (m_mysql) mysql_close(m_mysql);
}

bool DBManager::exec(const QString& sql) {
    LOG << "EXEC:" << sql;
    if (mysql_query(m_mysql, sql.toUtf8().constData())) {
        LOG << "ERROR:" << mysql_error(m_mysql);
        return false;
    }
    return true;
}

MYSQL_RES* DBManager::query(const QString& sql) {
    LOG << "QUERY:" << sql;
    if (mysql_query(m_mysql, sql.toUtf8().constData())) {
        LOG << "ERROR:" << mysql_error(m_mysql);
        return nullptr;
    }
    return mysql_store_result(m_mysql);
}

QString DBManager::lastError() const {
    return mysql_error(m_mysql);
}

DBManager& DBManager::instance() {
    static DBManager inst;
    return inst;
}
